<template>
  <div class="app-container">
    <el-form v-permission="['shop:detail']" ref="dataForm" :rules="rules" :model="shop" label-width="80px" class="padding-content">
      <el-row type="flex" class="row-bg">
        <el-col :span="10">
          <el-form-item label="门店名称" prop="name">
            <el-input v-model="shop.name" placeholder="请输入门店名称" maxlength="50"/>
          </el-form-item>
          <el-form-item label="电话号码" prop="phone">
            <el-input v-model="shop.phone" placeholder="请输入门店电话号码" maxlength="50"/>
          </el-form-item>
          <el-form-item label="门店地址" prop="address">
            <el-tooltip class="item" effect="dark" content="请点击右侧地图定位地址坐标" placement="top">
              <el-input v-model="shop.address" placeholder="请输入门店地址" maxlength="150"/>
            </el-tooltip>
          </el-form-item>
          <el-form-item v-if="shop.latitude && shop.longitude">
            经度:&nbsp;<span>{{ shop.longitude }}</span>&nbsp;
            维度:&nbsp;<span>{{ shop.latitude }}</span>
          </el-form-item>
          <el-form-item label="营业时间" prop="name">
            <el-time-select v-model="shop.startTime" :picker-options="{start: '06:00',step: '00:15',end: '24:00'}" placeholder="起始时间"/>
            <el-time-select v-model="shop.endTime" :picker-options="{start: '06:00',step: '00:15',end: '24:00',minTime: shop.startTime}" placeholder="结束时间"/>
          </el-form-item>
          <el-form-item label="门店LOGO">
            <uploader :file-list.sync="fileList" @success="uploadCoverSuccess" @remove="removeCoverSuccess"/>
          </el-form-item>
        </el-col>
        <el-col :span="1"/>
        <el-col :span="13"><div id="mapContainer"/></el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="门店图片">
            <uploader :limit="6" :file-list.sync="imgs" @success="uploadImgsSuccess" @remove="removeImgsSuccess"/>
            <el-alert type="success" description="最多上传6张图片 图片大小建议 520 x 280像素"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="门店简介" prop="tag">
        <editor :init="editorInit" v-model="shop.remark"/>
      </el-form-item>
    </el-form>
    <div class="text-center" style="margin-top:1em">
      <el-button v-permission="['shop:merge']" type="primary" @click="save">保存</el-button>
    </div>
  </div>
</template>
<script>
import { CommonService } from '@/api/CommonService'
import { ShopService } from '@/api/ShopService'
import Editor from '@tinymce/tinymce-vue'
import Uploader from '@/components/Uploader'
import { Notify } from '@/utils/notify'
import { get } from 'scriptjs'
import { TENCENT_MAP_KEY } from '@/utils/index'

export default {
  name: 'Store',
  components: { Uploader, Editor },
  data() {
    return {
      editorInit: {
        language: 'zh_CN',
        convert_urls: false, height: 300,
        plugins: ['advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'],
        toolbar: ['searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          CommonService.uploadFile(formData).then(res => {
            success(res.url)
          }).catch(() => {
            failure('上传失败，请重新上传')
          })
        }
      },
      fileList: [], imgs: [], shop: { phone: undefined, name: '', address: undefined, remark: undefined, logo: undefined, url: '', longitude: undefined, latitude: undefined, startTime: undefined, endTime: undefined, pics: [] },
      mapInfoWindow: undefined, map: undefined,
      dataForm: { id: undefined, phone: undefined, name: undefined, address: undefined, longitude: undefined, latitude: undefined },
      rules: {
        name: [{ required: true, message: '门店名称不能为空', trigger: 'blur' }],
        address: [{ required: true, message: '门店地址不能为空', trigger: 'blur' }],
        phone: [{ required: true, message: '门店电话号码不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.loadShopInfo()
  },
  methods: {
    loadShopInfo() {
      ShopService.getShop().then(res => {
        this.shop = res
        if (this.shop.logo) {
          this.fileList = [{ url: res.url }]
        }
        if (this.shop.pics) {
          this.imgs = this.shop.pics
        }
        this.loadShopMap()
      })
    },
    loadShopMap() {
      const exist = window.hasOwnProperty('TMap')
      if (exist) {
        this.renderMap()
      } else {
        const url = 'https://map.qq.com/api/gljs?v=1.exp&key=' + TENCENT_MAP_KEY
        get(url, () => {
          this.renderMap()
        })
      }
    },
    renderMap() {
      const that = this
      let lat = 39.984104
      let lng = 116.307503
      if (that.shop.latitude && that.shop.longitude) {
        lat = that.shop.latitude
        lng = that.shop.longitude
      }
      this.$nextTick(() => {
        const center = new window.TMap.LatLng(lat, lng)
        document.getElementById('mapContainer').innerHTML = ''
        that.map = new window.TMap.Map(document.getElementById('mapContainer'), { center: center, zoom: 16 })
        that.mapInfoWindow = new window.TMap.InfoWindow({ map: that.map, position: center,
          content: '<div><img width="90px" height="45px" src=' + that.shop.url + '>' + '<p>' + that.shop.name + '</p></div>'
        })
        that.map.on('click', function(evt) {
          that.shop.latitude = evt.latLng.getLat().toFixed(6)
          that.shop.longitude = evt.latLng.getLng().toFixed(6)
          that.mapInfoWindow.setPosition(evt.latLng)
          that.$forceUpdate()
        })
      })
    },
    uploadCoverSuccess(data) {
      this.shop.url = data.url
      this.shop.logo = data.path
    },
    removeCoverSuccess() {
      this.shop.url = undefined
      this.shop.logo = undefined
    },
    uploadImgsSuccess(data) {
      const count = this.shop.pics.length
      this.shop.pics[count] = { seq: count + 1, originalImg: data.path }
    },
    removeImgsSuccess(index) {
      this.shop.pics.splice(index, 1)
      this.shop.pics.forEach((item, seq) => {
        item.seq = seq + 1
      })
    },
    save() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          ShopService.saveShop(this.shop).then(() => {
            Notify.success(this, '保存成功')
            this.renderMap()
          })
        }
      })
    }
  }
}
</script>
